/**
 * 移动端路由生成
 */
import CommonUtil from '../utils/common'
import ArrayUtil from '../utils/array'
import { cloneDeep, omitBy } from 'lodash'
import URLUtil from '../utils/url'
import clone from 'clone'

export default (dataList, router) => {
  const { routeMap, dynamic } = router.getRouteConfig('mobile'),
    actionMap = {}, menuList = [],
    map = {}, routeList = [],
    routerPath = []

  // 缓存按钮权限
  dataList.map(data => {
    if (data.type === '3') {
      actionMap[data.parentId] = actionMap[data.parentId] || []
      actionMap[data.parentId].push(data.code.split(':').pop())
    }
  })

  dataList.map(data => {
    let query = null,
      url = null
    if (data.mobileUrl) {
      query = URLUtil.getURLParams(data.mobileUrl) || {}
      url = data.mobileUrl.split('?')[0]
    }

    // 从本地路由配置中获取路由
    let route = routeMap[url] || dynamic[url]
    if (route) {
      route = clone(route)

      if (query.menuId) {
        route.path = `${url}/${query.menuId}`
        route.meta.realPath = url
      }
      // 合并菜单 meta 到路由
      CommonUtil.merge(route.meta, {
        id: data.id,
        parentId: data.parentId,
        title: data.name,
        hidden: data.type == '3' ? true : CommonUtil.toBool(data.hidden),
        icon: data.icon,
        type: data.type
      })

      // 转存在 path 路径上配置的参数
      route.query = query || {}

      // 添加功能权限
      route.meta.authorize = actionMap[route.meta.id] || []

      // 去除子路由中没有 path 的子节点（功能按钮），或标记为绝对路径的子路由
      route.children = route.children?.filter(child => child.path && !child.meta.absolute) || []

      map[route.meta.id] = route
      routeList.push(route)
    } else if (url && !routerPath.includes(url)) {
      // 本地路由配置中未找到，且返回数据中存在路由地址，则生成新的路由
      route = {
        path: url,
        component: router.getView(data.component),
        meta: {
          id: data.id,
          parentId: data.parentId,
          title: data.name,
          hidden: data.type == '3' ? true : CommonUtil.toBool(data.hidden),
          icon: data.icon,
          type: data.type
        },
        query: query,
        children: []
      }

      // 添加功能权限
      route.meta.authorize = actionMap[route.meta.id] || []

      map[route.meta.id] = route
      routeList.push(route)
      routerPath.push(url)
    }
  })

  // 构建本地注册的路由及菜单
  const roots = router.getRoots(),
    root = roots.find(item => item.path === '/' || item.path === '')

  // 构建本地路由
  root.children = ArrayUtil.flat(cloneDeep(root.children || [])).map(child => {
    if (!child.path.startsWith('/') && !child.path.startsWith('https://') && !child.path.startsWith('http://')) {
      // 相对路径转绝对路径
      let pathList = ArrayUtil.getParents(child)
      pathList = pathList.filter(p => p.path && !p.path.startsWith('https://') && !p.path.startsWith('http://')).map(p => p.path)
      child.path = `${pathList.join('/')}/${child.path}`
    }
    child.meta = child.meta || {}
    return child
  })

  // 如路由地址为其他根路由地址开头的，则将路由添加到对应根路由的 children 中
  roots.map(root => {
    if (root.path == '/') return
    root.children = root.children || []
    Object.keys(map).map(id => {
      const route = map[id]
      if (route.path.startsWith(`${root.path}/`) && route.path != root.path) {
        root.children.push(route) && routeList.splice(routeList.indexOf(route), 1)
      }
    })
  })

  // 追加新的权限路由到 root 路由下
  root.children = root.children.concat(routeList.filter(route => route.meta.absolute || !route._parent))

  // 设置根路由的默认重定向地址
  roots.find(node => {
    return setDefaultRedirect(root)
  })
  return { roots }
}

function setDefaultRedirect (root) {
  if (root.redirect) {
    return true
  }
  root.redirect = root.children[0].path
}